//
//  CourseTeacherViewController.m
//  e-Learning
//
//  Created by rimi on 16/6/16.
//  Copyright © 2016年 YJ. All rights reserved.
//

#import "CourseTeacherViewController.h"
#import "MoviePlayerViewController.h"
#import "CustomTableViewCell.h"
#import "LessonTableViewCell.h"

@interface CourseTeacherViewController ()<UITableViewDataSource,UITableViewDelegate,CustomTableViewCellDelegate,UITextViewDelegate,LessonTableViewCellDelegate>
{
    //这个界面与Home不同, Home用的懒加载,复用了内存的同一视图,这里每次换控制器时,移除旧的视图,下次加载时, 是一个新开辟的东西  而不是之前Home那样懒加载的旧图,是一个新的视图,所以不会保持在原来的位置 . 不同的方式,需要什么用什么.
    UIView *mainContainerVu;
    UIView *detailContainerVu;
    UIScrollView *titleScrollVu;
    UITableView *infoTableVu;
    NSDictionary *infoTeachersDic;
    NSArray *titleKeys;
    NSArray *lessonKeys;
    NSArray *currenDataSource;
    NSMutableArray *titleBtnArray;
    NSString *currentTeacherID;
    UIView *clearVu;
    UIView *alertVu;
    NSString *questionString;
    NSDictionary *lessonTableViewDataSource;
    int selectTitleBtnIndex;
}
@end

@implementation CourseTeacherViewController

#pragma mark - LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    mainContainerVu = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:mainContainerVu];
    [self titleScrollViewDataDeal];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [mainContainerVu removeFromSuperview];
    mainContainerVu = nil;
    [detailContainerVu removeFromSuperview];
    detailContainerVu = nil;
    
}

#pragma mark - Action Events



#pragma mark 1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣

- (void)titleScrollViewDataDeal{
    [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_teacher!getClandTe.action")) parameters:@{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]} finish:^(id responseObject, NSError *error) {
        if ([responseObject[@"status"] intValue] == 104) {
            //重复登陆
        } else if ([responseObject[@"status"] intValue] == 1){
            //请求成功
            infoTeachersDic = responseObject[@"data"][@"teachers"];
            [self titleBtnAddIntoTitleScrollVu:responseObject[@"data"][@"classify"]];
        }
    }];
}

- (void)titleBtnAddIntoTitleScrollVu:(NSDictionary *)titleBtnDic{
    
    titleScrollVu = [[UIScrollView alloc] initWithFrame:CGRectMake(0, Screen_Height/9, Screen_Width, Screen_Height/9)];
    titleScrollVu.showsHorizontalScrollIndicator = NO;
    [mainContainerVu addSubview:titleScrollVu];
    
    titleKeys = [titleBtnDic allKeys];
    
    NSMutableArray *titleNames = [@[] mutableCopy];
    for (int i = 0; i < titleKeys.count; i ++) {
        [titleNames addObject:titleBtnDic[titleKeys[i]]];
    }
    titleBtnArray = [@[] mutableCopy];
    int left = 0;
    for (int i = 0; i < titleNames.count; i ++) {
        if (i == 0) {
            left += Screen_Height/9/4;
        } else {
            left += Screen_Height/9/4/3;
        }
        CustomBtn *titleBtn = [[CustomBtn alloc] initWithFrame:CGRectMake(i*(Screen_Width/3-Screen_Height/9/4)+left, Screen_Height/9/4, Screen_Width/3-Screen_Height/9/4, Screen_Height/9-Screen_Height/9/4) index:i];
        [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [titleBtn setTitle:titleNames[i] forState:UIControlStateNormal];
        titleBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        [titleBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        titleBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        titleBtn.layer.borderWidth = 1.5;
        titleBtn.titleLabel.font = [UIFont systemFontOfSize:24];
        [titleBtnArray addObject:titleBtn];
        [titleScrollVu addSubview:titleBtn];
    }
    //一来默认第一个的处理
    selectTitleBtnIndex = 0;
    CustomBtn * btn = titleBtnArray[selectTitleBtnIndex];
    btn.layer.borderColor = [UIColor redColor].CGColor;
    
    [self tableViewDeal];
    
    titleScrollVu.contentSize = CGSizeMake((Screen_Width/3-Screen_Height/9/4)*titleNames.count+2*Screen_Height/9/4+(titleNames.count-1)*Screen_Height/9/4/3, Screen_Height/9);
    
}

- (void)tableViewDeal{
    [infoTableVu removeFromSuperview];
    infoTableVu = [[UITableView alloc] initWithFrame:CGRectMake(0, Screen_Height/9*2-0.5, Screen_Width, Screen_Height/9*6) style:UITableViewStylePlain];
    infoTableVu.tag = 100;
    NSString *currentKey = nil;
    switch (selectTitleBtnIndex) {
        case 0:currentKey = titleKeys[0];break;
        case 1:currentKey = titleKeys[1];break;
        case 2:currentKey = titleKeys[2];break;
        case 3:currentKey = titleKeys[3];break;
        default:break;
    }
    currenDataSource = infoTeachersDic[currentKey];
    //表格
    [infoTableVu registerClass:[CustomTableViewCell class] forCellReuseIdentifier:@"cell"];
    infoTableVu.separatorStyle = UITableViewCellSeparatorStyleNone;
    infoTableVu.dataSource = self;
    infoTableVu.delegate = self;
    infoTableVu.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [mainContainerVu addSubview:infoTableVu];
}

- (void)titleBtnClick:(CustomBtn *)sender{
    if (selectTitleBtnIndex == sender.index) {
        return;
    }
    selectTitleBtnIndex = sender.index;
    for (int i = 0; i < titleBtnArray.count; i ++) {
        CustomBtn * currentBtn = titleBtnArray[i];
        if (i == selectTitleBtnIndex){
            currentBtn.layer.borderColor = [UIColor redColor].CGColor;
        } else {
            currentBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
        }
    }
    //表格处理
    [self tableViewDeal];
}

#pragma mark 1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣1️⃣
#pragma mark 2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣
- (void)question{
    //提示框
    //透明层
    clearVu = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    clearVu.backgroundColor = [UIColor whiteColor];
    clearVu.alpha = 0.7;
    [mainContainerVu addSubview:clearVu];
    //灰层
    alertVu = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width/2, Screen_Height/2)];
    alertVu.center = mainContainerVu.center;
    alertVu.alpha = 0.9;
    alertVu.backgroundColor = [UIColor grayColor];
    [mainContainerVu addSubview:alertVu];
    //文本框
    UITextView *text = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width/2*0.9, Screen_Height/2*0.5)];
    text.center = CGPointMake(Screen_Width/2/2, Screen_Height/2/2);
    text.font = [UIFont systemFontOfSize:20];
    text.backgroundColor = [UIColor whiteColor];
    text.delegate = self;
    [alertVu addSubview:text];
    //取消
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(Screen_Width/2/9*2,Screen_Height/2*0.8, Screen_Width/2/9*2, Screen_Width/2/9*2/3)];
    cancelBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cancelBtn.layer.borderWidth = 1.5;
    cancelBtn.backgroundColor = [UIColor lightGrayColor];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:24];
    [cancelBtn addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [alertVu addSubview:cancelBtn];
    //确定
    UIButton *confirmBtn = [[UIButton alloc] initWithFrame:CGRectMake(Screen_Width/2/9*5, Screen_Height/2*0.8, Screen_Width/2/9*2, Screen_Width/2/9*2/3)];
    confirmBtn.layer.borderColor = [UIColor redColor].CGColor;
    confirmBtn.layer.borderWidth = 1.5;
    confirmBtn.backgroundColor = [UIColor lightGrayColor];
    [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    confirmBtn.titleLabel.font = [UIFont systemFontOfSize:24];
    [confirmBtn addTarget:self action:@selector(confirm:) forControlEvents:UIControlEventTouchUpInside];
    [alertVu addSubview:confirmBtn];
}

- (void)cancel{
    //取消提问
    [clearVu removeFromSuperview];
    clearVu = nil;
    [alertVu removeFromSuperview];
    alertVu = nil;
    questionString = nil;
}

- (void)confirm:(UIButton *)sender{
    //提交提问
    if (!questionString) {
        UIAlertController *null = [UIAlertController alertControllerWithTitle:@"提示" message:@"问题不能为空" preferredStyle:UIAlertControllerStyleAlert];
        [null addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:null animated:YES completion:nil];
    } else {
        [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_teacher!askForTeacher.action")) parameters:@{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"],@"content":questionString,@"id":currentTeacherID} finish:^(id responseObject, NSError *error) {
            if ([responseObject[@"status"] intValue] == 104) {
                //重复登陆
                NSLog(@"重复登陆");
            } else if ([responseObject[@"status"] intValue] == 1){
                //提交成功;
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"问题已提交成功" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self cancel];
                }]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }
}


- (void)lession{
    [mainContainerVu removeFromSuperview];
    detailContainerVu = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:detailContainerVu];
    //返回按钮
    UIButton *detailBackBtn = [[UIButton alloc] initWithFrame:CGRectMake(Screen_Height/9/2, Screen_Height/9*6+Screen_Height/9/2, Screen_Height/9, Screen_Height/9)];
    [detailBackBtn setBackgroundImage:[UIImage imageNamed:@"activity_back.png"] forState:UIControlStateNormal];
    [detailBackBtn addTarget:self action:@selector(detailBack) forControlEvents:UIControlEventTouchUpInside];
    [detailContainerVu addSubview:detailBackBtn];
    
    [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_teacher!getTeacherCourse.action")) parameters:@{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"],@"id":currentTeacherID} finish:^(id responseObject, NSError *error) {
        if ([responseObject[@"status"] intValue] == 104) {
            //重复登陆
            NSLog(@"重复登陆");
        } else if ([responseObject[@"status"] intValue] == 1){
            //请求成功
            lessonTableViewDataSource = responseObject[@"data"];
            [self lessonTableView];
        }
    }];
}

- (void)lessonTableView{
    lessonKeys = [lessonTableViewDataSource.allKeys sortedArrayUsingSelector:@selector(compare:)];
    UITableView *lessonTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, Screen_Height/9, Screen_Width, Screen_Height/9*7) style:UITableViewStylePlain];
    [lessonTableView registerClass:[LessonTableViewCell class] forCellReuseIdentifier:@"lesson"];
    [detailContainerVu insertSubview:lessonTableView atIndex:0];
    lessonTableView.tag = 101;
    lessonTableView.dataSource = self;
    lessonTableView.delegate = self;
    lessonTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
}

- (void)detailBack{
    [detailContainerVu removeFromSuperview];
    detailContainerVu = nil;
    [self.view addSubview:mainContainerVu];
}

- (void)answer{
    [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_teacher!getTeacherQuestions.action")) parameters:@{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"],@"id":currentTeacherID,@"pageNum":@(1),@"pagesize":@(10)} finish:^(id responseObject, NSError *error) {
        if ([responseObject[@"status"] intValue] == 104){
            //重复登陆操作
            NSLog(@"重复登陆");
        } else if ([responseObject[@"status"] intValue] == 1) {
            NSArray *dataArray = responseObject[@"data"];
            if (dataArray.count == 0) {
                //空信息
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该讲师暂无答疑信息" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
            } else {
                //非空信息
            }
        }
    }];
}

#pragma mark 2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣2️⃣
#pragma mark 3️⃣3️⃣3️⃣3️⃣3️⃣3️⃣3️⃣3️⃣3️⃣3️⃣3️⃣



#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView{
    questionString = textView.text;
}
#pragma mark - CustomTableViewCellDelegate

- (void)tapButtonID:(NSString *)teacherID btnTitleIndex:(int)index{
    currentTeacherID = teacherID;
    switch (index) {
        case 1:[self question];break;
        case 2:[self lession];break;
        case 3:[self answer]; break;
        default:break;
    }
}

#pragma mark - LessonTableViewCellDelegate     视频跳转

- (void)enterVideoVu:(NSString *)videoID countLesson:(int)count{
    //作页面切换, 跳转视频界面
    
    //加载操作
    UIAlertView *loading = [[UIAlertView alloc] initWithTitle:@"提示" message:@"视频正在加载中" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [loading show];
    
    [[NetWorkTools sharedTools] requestMethod:POST URL:sid(url(@"front_video!videoList.action")) parameters:@{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"],@"id":videoID,@"uid":[[NSUserDefaults standardUserDefaults] objectForKey:@"uid"]} finish:^(id responseObject, NSError *error) {
        if ([responseObject[@"status"] intValue] == 104) {
            NSLog(@"重复登陆");
        } else if ([responseObject[@"status"] intValue] == 1) {
            //判断有没有视频  listName.cout
            NSArray *videoArray = responseObject[@"data"][@"listName"];
            if (videoArray.count == 0) {
                //提示没有课程
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [loading dismissWithClickedButtonIndex:0 animated:YES];
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该课程还没有可播放的教学视频" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                    [alert show];
                });
            } else {
                //有视频跳转操作
                [loading dismissWithClickedButtonIndex:0 animated:YES];
                //取视频的url地址存起
                NSMutableArray *urlList = [@[] mutableCopy];
                NSMutableArray *idList = [@[] mutableCopy];
                for (int i = 0; i < videoArray.count; i ++) {
                    [urlList addObject:url([EncryptTool decodeString:videoArray[i][@"url"]])];
                    [idList addObject:videoArray[i][@"id"]];
                }
                //切换到视频操作界面
                MoviePlayerViewController *movieVc = [MoviePlayerViewController new];
                movieVc.playerListArray = urlList;
                movieVc.playerListIDArray = idList;
                movieVc.lessonID = videoID;
                [self presentViewController:movieVc animated:YES completion:nil];
            }
        }
    }];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 100) {
        CustomTableViewCell * cell =  [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        [cell.imageVu sd_setImageWithURL:[NSURL URLWithString:url(currenDataSource[indexPath.row][@"pic"])] placeholderImage:nil options:SDWebImageProgressiveDownload];
        cell.name.text = currenDataSource[indexPath.row][@"name"];
        cell.introduce.text = currenDataSource[indexPath.row][@"abstract1"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.teacherID = currenDataSource[indexPath.row][@"id"];
        cell.delegate = self;
        return cell;
    } else {
        LessonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"lesson" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.lessonTitle.text = lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"classify"];
        cell.typeTitle.text = lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"lname"];
        cell.teacherName.text = lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"teacher"];
        cell.students.text = [[lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"student"] stringValue] stringByAppendingString:@"人正在学习"];
        cell.discuss.text = [[lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"discuss"] stringValue] stringByAppendingString:@"评价"];
        cell.learnTime.text = [[@"共" stringByAppendingString:[lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"countLession"] stringValue]] stringByAppendingString:@"课时"];
        [cell.imageBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:url(lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"img"])] forState:UIControlStateNormal placeholderImage:nil options:SDWebImageProgressiveDownload];
        cell.videoID = lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"id"];
        cell.lessonCount = [lessonTableViewDataSource[lessonKeys[indexPath.row]][0][@"countLession"] intValue];
        cell.delegate = self;
        return cell;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView.tag == 100) {
        return currenDataSource.count;
    } else {
        return lessonTableViewDataSource.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == 100) {
        return Screen_Height/9*7/3;
    } else {
        return Screen_Height/2;
    }
    
}


@end
